﻿#include "dailyschedule.h"
#include <qlistwidget.h>
#include <QCoreApplication>  // 添加这一行
DailySchedule::DailySchedule(QWidget* parent)
    : QWidget(parent)
    , m_currentDate(QDate::currentDate())
{
    setWindowTitle("每日作息表");

    // 设置数据目录（跨平台兼容）
    m_dataDir = QCoreApplication::applicationDirPath() + "/DailyScheduleData";
    ensureDataDirectory();

    initUI();
    loadScheduleForDate(m_currentDate);
}
void DailySchedule::onImportRoutineClicked()
{
    // 初始化日常任务（如果还没初始化）
    if (m_routineTasks.isEmpty()) {
        initRoutineTasks();
    }

    // 创建对话框
    QDialog dialog(this);
    dialog.setWindowTitle("导入日常内容");
    //dialog.setMinimumSize(300, 400);

    QVBoxLayout* layout = new QVBoxLayout(&dialog);

    // 创建列表控件
    listWidget = new QListWidget(&dialog);
    listWidget->setSelectionMode(QAbstractItemView::SingleSelection);

    // 添加日常任务到列表（按时间排序）
    QList<QString> keys = m_routineTasks.keys();
    std::sort(keys.begin(), keys.end(), [this](const QString& a, const QString& b) {
        return m_routineTasks[a].second < m_routineTasks[b].second;
        });

    for (const QString& key : keys) {
        QString timeStr = m_routineTasks[key].first;
        QString displayText = QString("%1 - %2").arg(timeStr).arg(key);
        QListWidgetItem* item = new QListWidgetItem(displayText);
        item->setData(Qt::UserRole, key);  // 存储任务名称
        listWidget->addItem(item);
    }

    // 按钮布局
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    QPushButton* okButton = new QPushButton("导入选中项", &dialog);
    QPushButton* oneKeyButton = new QPushButton("一键导入", &dialog);
    QPushButton* cancelButton = new QPushButton("取消", &dialog);


    buttonLayout->addWidget(oneKeyButton);
    buttonLayout->addWidget(okButton);
    buttonLayout->addWidget(cancelButton);

    // 添加到主布局
    layout->addWidget(new QLabel("选择要导入的日常任务:"));
    layout->addWidget(listWidget);
    layout->addLayout(buttonLayout);

    // 连接信号
    connect(oneKeyButton, &QPushButton::clicked, [this]() {
        for (int i = 0; i < listWidget->count(); ++i) {
            QString taskName = listWidget->item(i)->data(Qt::UserRole).toString();
            // 获取任务信息
            QString timeStr = m_routineTasks[taskName].first;
            int minutes = m_routineTasks[taskName].second;

            // 在表格中添加新行
            int row = m_table->rowCount();
            m_table->insertRow(row);

            // 初始化行
            initializeRow(row);

            // 设置时间
            QTableWidgetItem* timeItem = m_table->item(row, 0);
            timeItem->setData(Qt::UserRole, minutes);
            timeItem->setText(timeStr);

            // 设置任务
            QTableWidgetItem* taskItem = m_table->item(row, 1);
            taskItem->setText(taskName);
            // 自动滚动到新添加的最后一行
            m_table->scrollToBottom();


        }
        // 在所有操作完成后强制更新
        m_table->viewport()->update();
        
        });
    connect(okButton, &QPushButton::clicked, &dialog, &QDialog::accept);
    connect(cancelButton, &QPushButton::clicked, &dialog, &QDialog::reject);
    connect(listWidget, &QListWidget::itemDoubleClicked, &dialog, &QDialog::accept);
    listWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
    // 显示对话框
    if (dialog.exec() == QDialog::Accepted) {
        QList<QListWidgetItem*> selectedItems = listWidget->selectedItems();
        if (!selectedItems.isEmpty()) {
            for (QListWidgetItem* item : selectedItems) {
                QString taskName = item->data(Qt::UserRole).toString();

                if (m_routineTasks.contains(taskName)) {
                    // 获取任务信息
                    QString timeStr = m_routineTasks[taskName].first;
                    int minutes = m_routineTasks[taskName].second;

                    // 在表格中添加新行
                    int row = m_table->rowCount();
                    m_table->insertRow(row);

                    // 初始化行
                    initializeRow(row);

                    // 设置时间
                    QTableWidgetItem* timeItem = m_table->item(row, 0);
                    timeItem->setData(Qt::UserRole, minutes);
                    timeItem->setText(timeStr);

                    // 设置任务
                    QTableWidgetItem* taskItem = m_table->item(row, 1);
                    taskItem->setText(taskName);
                }
            }
            // 自动滚动到新添加的最后一行
            m_table->scrollToBottom();
        }
    }
}

void DailySchedule::initializeRow(int row)
{
    // 设置行高
    m_table->setRowHeight(row, 40);

    // 初始化所有列
    for (int col = 0; col < m_table->columnCount(); ++col) {
        if (!m_table->item(row, col)) {
            QTableWidgetItem* item = new QTableWidgetItem();

            if (col == 4) { // 完成状态列 - 复选框
                item->setCheckState(Qt::Unchecked);
                item->setTextAlignment(Qt::AlignCenter);
                item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
            }
            else if (col == 0) { // 时间列
                item->setData(Qt::UserRole, 0); // 默认时间值
                item->setText("00:00"); // 默认显示文本
            }
            else { // 其他文本列
                item->setText("");
            }

            m_table->setItem(row, col, item);
        }
    }
}
// DailySchedule.cpp
void DailySchedule::initRoutineTasks()
{
    // 高中日常作息安排（时间格式：HH:mm，分钟数从0点开始计算）
    m_routineTasks.clear();

    // 早晨
    m_routineTasks["起床"] = QPair<QString, int>("06:30", 390);   // 6:30 = 6*60+30 = 390分钟
    m_routineTasks["晨读"] = QPair<QString, int>("06:45", 405);
    m_routineTasks["早餐"] = QPair<QString, int>("07:15", 435);

    // 上午课程
    m_routineTasks["第一节课"] = QPair<QString, int>("08:00", 480);
    m_routineTasks["第二节课"] = QPair<QString, int>("08:50", 530);
    m_routineTasks["课间操"] = QPair<QString, int>("09:40", 580);
    m_routineTasks["第三节课"] = QPair<QString, int>("10:10", 610);
    m_routineTasks["第四节课"] = QPair<QString, int>("11:00", 660);

    // 中午
    m_routineTasks["午餐"] = QPair<QString, int>("12:00", 720);
    m_routineTasks["午休"] = QPair<QString, int>("12:40", 760);

    // 下午课程
    m_routineTasks["第五节课"] = QPair<QString, int>("14:00", 840);
    m_routineTasks["第六节课"] = QPair<QString, int>("14:50", 890);
    m_routineTasks["眼保健操"] = QPair<QString, int>("15:40", 940);
    m_routineTasks["第七节课"] = QPair<QString, int>("16:00", 960);
    m_routineTasks["第八节课"] = QPair<QString, int>("16:50", 1010);

    // 课后活动
    m_routineTasks["课外活动"] = QPair<QString, int>("17:30", 1050);
    m_routineTasks["晚餐"] = QPair<QString, int>("18:30", 1110);

    // 晚自习
    m_routineTasks["晚自习第一节"] = QPair<QString, int>("19:30", 1170);
    m_routineTasks["晚自习第二节"] = QPair<QString, int>("20:20", 1220);

    // 就寝
    m_routineTasks["洗漱准备"] = QPair<QString, int>("21:30", 1290);
    m_routineTasks["熄灯就寝"] = QPair<QString, int>("22:00", 1320);
}

DailySchedule::~DailySchedule()
{
    // 退出时自动保存
    saveScheduleForDate(m_currentDate);
}

void DailySchedule::initUI()
{
    // 设置整体样式
    setStyleSheet(R"(
        QWidget {
            font-family: "Microsoft YaHei", "Segoe UI";
            font-size: 12px;
        }
        QGroupBox {
            font-weight: bold;
            border: 2px solid #cccccc;
            border-radius: 8px;
            margin-top: 1ex;
            padding-top: 10px;
        }
        QGroupBox::title {
            subcontrol-origin: margin;
            subcontrol-position: top center;
            padding: 0 8px;
            background-color: white;
        }
        QPushButton {
            background-color: #4CAF50;
            border: none;
            color: white;
            padding: 8px 16px;
            border-radius: 4px;
            font-weight: bold;
        }
        QPushButton:hover {
            background-color: #45a049;
        }
        QPushButton:pressed {
            background-color: #3d8b40;
        }
        QPushButton:disabled {
            background-color: #cccccc;
            color: #666666;
        }
        QTableWidget {
            gridline-color: #d0d0d0;
            selection-background-color: #e3f2fd;
            border: 1px solid #cccccc;
        }
        QTableWidget::item {
            padding: 8px;
        }
        QHeaderView::section {
            background-color: #f0f0f0;
            padding: 8px;
            border: 1px solid #d0d0d0;
            font-weight: bold;
        }
        QSlider::groove:horizontal {
            border: 1px solid #999999;
            height: 8px;
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #B1B1B1, stop:1 #c4c4c4);
            margin: 2px 0;
            border-radius: 4px;
        }
        QSlider::handle:horizontal {
            background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #4CAF50, stop:1 #45a049);
            border: 1px solid #5c5c5c;
            width: 18px;
            margin: -2px 0;
            border-radius: 9px;
        }
    )");

    QHBoxLayout* mainLayout = new QHBoxLayout(this);
    QGroupBox* dateGroup = new QGroupBox("📅 每日作息表");
    QVBoxLayout* dateLayout = new QVBoxLayout(dateGroup);

    m_dateEdit = new QDateEdit;
    m_dateEdit->setDate(m_currentDate);
    m_dateEdit->setCalendarPopup(true);
    m_dateEdit->setDisplayFormat("yyyy年MM月dd日 dddd");
    m_dateEdit->setStyleSheet("QDateEdit { padding: 8px; font-size: 14px; }");

    dateLayout->addWidget(new QLabel("选择日期:"));
    dateLayout->addWidget(m_dateEdit);

    mainLayout->addWidget(dateGroup);

    // 在适当的位置添加导入按钮
    QPushButton* importButton = new QPushButton("导入日常内容", this);
    connect(importButton, &QPushButton::clicked, this, &DailySchedule::onImportRoutineClicked);
    dateLayout->addWidget(importButton);
    dateLayout->addStretch();
    m_totalTasksLabel = new QLabel("总任务: 0");
    m_completedLabel = new QLabel("已完成: 0");
    m_productivityLabel = new QLabel("效率: 0%");

    QString statsStyle = "QLabel { font-size: 14px; font-weight: bold; padding: 8px; background-color: #e8f5e8; border-radius: 4px; }";
    m_totalTasksLabel->setStyleSheet(statsStyle);
    m_completedLabel->setStyleSheet(statsStyle);
    m_productivityLabel->setStyleSheet(statsStyle);




    // 表格区域
    QGroupBox* tableGroup = new QGroupBox("作息安排");
    // 同时设置最小尺寸和大小策略
    tableGroup->setMinimumSize(100, 100); // 设置最小尺寸
    tableGroup->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    QVBoxLayout* tableLayout = new QVBoxLayout(tableGroup);
    tableLayout->setContentsMargins(5, 5, 5, 5); // 设置边距

    initTable();

    //设置行最小高度

    m_table->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    // 如果表格有固定的行列，设置表头拉伸
    m_table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    m_table->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    tableLayout->addWidget(m_table);

    // 在mainLayout中设置拉伸
    mainLayout->addWidget(tableGroup, 1); // 拉伸因子为1
    mainLayout->setContentsMargins(10, 10, 10, 10);


    QHBoxLayout* timeLayout = new QHBoxLayout();
    m_timeSlider = new QSlider(Qt::Horizontal);
    m_timeSlider->setRange(0, 143); // 0-23:59, 每10分钟一个间隔
    m_timeSlider->setValue(36); // 默认6:00

    m_timeLabel = new QLabel("06:00");
    m_timeLabel->setStyleSheet("QLabel { font-weight: bold; color: #2c3e50; min-width: 50px; }");

    timeLayout->addWidget(m_timeSlider);
    timeLayout->addWidget(m_timeLabel);

    // 按钮区域
    QHBoxLayout* btnLayout = new QHBoxLayout();
    m_addBtn = new QPushButton("➕ 添加事件");
    m_removeBtn = new QPushButton("➖ 删除选中");
    m_clearBtn = new QPushButton("🗑️ 清空今日");
    m_saveBtn = new QPushButton("💾 保存数据");
    m_loadBtn = new QPushButton("📂 加载数据");

    dateLayout->addWidget(m_addBtn);
    dateLayout->addWidget(m_removeBtn);
    dateLayout->addWidget(m_clearBtn);
    dateLayout->addWidget(m_saveBtn);
    dateLayout->addWidget(m_loadBtn);
    dateLayout->addStretch();


    dateLayout->addWidget(m_totalTasksLabel);
    dateLayout->addWidget(m_completedLabel);
    dateLayout->addWidget(m_productivityLabel);

    // 连接信号槽
    connect(m_dateEdit, &QDateEdit::dateChanged, this, &DailySchedule::onDateChanged);
    connect(m_timeSlider, &QSlider::valueChanged, this, &DailySchedule::onTimeSliderChanged);
    connect(m_addBtn, &QPushButton::clicked, this, &DailySchedule::onAddScheduleClicked);
    connect(m_removeBtn, &QPushButton::clicked, this, &DailySchedule::onRemoveScheduleClicked);
    connect(m_clearBtn, &QPushButton::clicked, this, &DailySchedule::onClearToday);
    connect(m_saveBtn, &QPushButton::clicked, this, &DailySchedule::onSaveData);
    connect(m_loadBtn, &QPushButton::clicked, this, &DailySchedule::onLoadData);
}

void DailySchedule::initTable()
{
    m_table = new QTableWidget(this);
    m_table->setColumnCount(5);
    m_table->setHorizontalHeaderLabels({ "时间", "任务", "反思输出", "目标调整", "完成状态" });

    // 设置列宽
    m_table->setColumnWidth(0, 50);  // 时间
    m_table->setColumnWidth(1, 150);  // 任务
    m_table->setColumnWidth(2, 150);  // 反思
    m_table->setColumnWidth(3, 200);  // 目标
    m_table->setColumnWidth(4, 100);  // 状态

    m_table->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_table->setSelectionMode(QAbstractItemView::SingleSelection);
    m_table->setAlternatingRowColors(true);
    m_table->setSortingEnabled(true);

    // 设置最小行高
    m_table->verticalHeader()->setMinimumSectionSize(50); // 设置最小行高为30像素
    m_table->verticalHeader()->setDefaultSectionSize(60); // 设置默认行高为40像素

    // 设置样式
    m_table->setStyleSheet(R"(
        QTableWidget {
            alternate-background-color: #f8f9fa;
            background-color: white;
        }
        QTableWidget::item:selected {
            background-color: #e3f2fd;
        }
    )");


}

void DailySchedule::onAddScheduleClicked()
{
    qDebug() << "添加事件按钮被点击";
    qDebug() << "当前日期:" << m_currentDate;
    qDebug() << "是否是今天:" << (m_currentDate == QDate::currentDate());

    // 获取当前时间
    int sliderValue =0;
    int hours = sliderValue / 6;
    int minutes = (sliderValue % 6) * 10;
    QTime time(hours, minutes);

    qDebug() << "时间滑块值:" << sliderValue;
    qDebug() << "计算的时间:" << time.toString("hh:mm");

    // 插入新行
    int row = m_table->rowCount();
    m_table->insertRow(row);

    qDebug() << "新行索引:" << row;

    // 时间列
    QTableWidgetItem* timeItem = new QTableWidgetItem(time.toString("hh:mm"));
    timeItem->setData(Qt::UserRole, sliderValue);
    timeItem->setTextAlignment(Qt::AlignCenter); // 设置居中对齐
    m_table->setItem(row, 0, timeItem);

    // 任务列
    QTableWidgetItem* taskItem = new QTableWidgetItem("点击设置任务...");
    taskItem->setTextAlignment(Qt::AlignCenter); // 设置居中对齐
    m_table->setItem(row, 1, taskItem);

    // 反思列
    QTableWidgetItem* reflectionItem = new QTableWidgetItem("点击进行...");
    reflectionItem->setTextAlignment(Qt::AlignCenter); // 设置居中对齐
    m_table->setItem(row, 2, reflectionItem);

    // 目标列
    QTableWidgetItem* goalItem = new QTableWidgetItem("点击设置目标...");
    goalItem->setTextAlignment(Qt::AlignCenter); // 设置居中对齐
    goalItem->setFlags(goalItem->flags() | Qt::ItemIsEditable);
    m_table->setItem(row, 3, goalItem);

    // 状态列
    QTableWidgetItem* statusItem = new QTableWidgetItem();
    statusItem->setCheckState(Qt::Unchecked);
    statusItem->setTextAlignment(Qt::AlignCenter); // 设置居中对齐
    m_table->setItem(row, 4, statusItem);

    qDebug() << "事件添加完成，当前行数:" << m_table->rowCount();

    // 连接状态改变信号
    connect(m_table->model(), &QAbstractItemModel::dataChanged,
        [this](const QModelIndex& topLeft, const QModelIndex& bottomRight) {
            qDebug() << "表格数据改变，列:" << topLeft.column();
            if (topLeft.column() == 4) {
                updateStatistics();
            }
        });

    updateStatistics();

    // 自动保存
    saveScheduleForDate(m_currentDate);

    qDebug() << "数据已保存";
}
void DailySchedule::onRemoveScheduleClicked()
{
    int currentRow = m_table->currentRow();
    if (currentRow >= 0) {
        m_table->removeRow(currentRow);
        updateStatistics();
        saveScheduleForDate(m_currentDate);
    }
    else {
        QMessageBox::information(this, "提示", "请先选择要删除的行");
    }
}

void DailySchedule::onDateChanged(const QDate& date)
{
    // 保存当前日期的数据
    saveScheduleForDate(m_currentDate);

    // 加载新日期的数据
    m_currentDate = date;
    loadScheduleForDate(date);

    // 如果是今天以及以后，启用编辑功能；否则只读
    bool isToday = (date>QDate::currentDate());
    m_addBtn->setEnabled(isToday);
    m_removeBtn->setEnabled(isToday);
    m_clearBtn->setEnabled(isToday);

    if (!isToday) {
        m_table->setEditTriggers(QAbstractItemView::NoEditTriggers);
    }
    else {
        m_table->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed);
    }
}

void DailySchedule::onTimeSliderChanged(int value)
{
    int hours = value / 6;
    int minutes = (value % 6) * 10;
    updateTimeDisplay(hours, minutes);
}

void DailySchedule::updateTimeDisplay(int hour, int minute)
{
    m_timeLabel->setText(QString("%1:%2")
        .arg(hour, 2, 10, QLatin1Char('0'))
        .arg(minute, 2, 10, QLatin1Char('0')));
}

void DailySchedule::onSaveData()
{
    saveScheduleForDate(m_currentDate);
    QMessageBox::information(this, "成功", "数据已保存！\n位置: " + getDataFilePath());
}

void DailySchedule::onLoadData()
{
    loadScheduleForDate(m_currentDate);
    QMessageBox::information(this, "成功", "数据已加载！");
}

void DailySchedule::onClearToday()
{
    if (QMessageBox::question(this, "确认清空",
        "确定要清空今日的所有作息事件吗？此操作不可撤销！") == QMessageBox::Yes) {
        clearCurrentDay();
    }
}

void DailySchedule::loadScheduleForDate(const QDate& date)
{
    QString filePath = m_dataDir + "/" + date.toString("yyyy-MM-dd") + ".json";
    QFile file(filePath);

    if (!file.exists()) {
        // 如果是今天，清空表格；如果是过去日期，保持空表
      /*  if (date == QDate::currentDate()) {
            clearCurrentDay();
        }
        else {
            m_table->setRowCount(0);
        }*/
        //过去也可以显示
        clearCurrentDay();
        updateStatistics();
        return;
    }

    if (!file.open(QIODevice::ReadOnly)) {
        QMessageBox::warning(this, "错误", "无法打开数据文件: " + filePath);
        return;
    }

    QByteArray data = file.readAll();
    file.close();

    QJsonDocument doc = QJsonDocument::fromJson(data);
    if (!doc.isObject()) {
        QMessageBox::warning(this, "错误", "数据文件格式错误");
        return;
    }


    jsonToSchedule(doc.object());
    updateStatistics();
}

void DailySchedule::saveScheduleForDate(const QDate& date)
{
    QString filePath = m_dataDir + "/" + date.toString("yyyy-MM-dd") + ".json";
    QFile file(filePath);

    if (!file.open(QIODevice::WriteOnly)) {
        QMessageBox::warning(this, "错误", "无法创建数据文件: " + filePath);
        return;
    }
    QJsonDocument doc(scheduleToJson());
    file.write(doc.toJson());
    file.close();
}

void DailySchedule::clearCurrentDay()
{
    m_table->setRowCount(0);
    updateStatistics();
    saveScheduleForDate(m_currentDate);
}

QString DailySchedule::getDataFilePath() const
{
    return m_dataDir + "/" + m_currentDate.toString("yyyy-MM-dd") + ".json";
}

void DailySchedule::ensureDataDirectory() const
{
    QDir dir;
    if (!dir.exists(m_dataDir)) {
        dir.mkpath(m_dataDir);
    }
}

QJsonObject DailySchedule::scheduleToJson() const
{
    QJsonObject root;
    QJsonArray schedules;


    for (int i = 0; i < m_table->rowCount(); ++i) {
        QJsonObject schedule;
        schedule["time"] = m_table->item(i, 0)->text();
        // 解决方案1：将QJsonValue转换为QString
        schedule["task"] = m_table->item(i, 1)->text();
        schedule["reflection"] = m_table->item(i, 2)->text();
        schedule["goal"] = m_table->item(i, 3)->text();
        schedule["completed"] = (m_table->item(i, 4)->checkState() == Qt::Checked);

        schedules.append(schedule);
    }

    root["schedules"] = schedules;
    root["date"] = m_currentDate.toString("yyyy-MM-dd");
    root["saved_at"] = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");

    return root;
}

void DailySchedule::jsonToSchedule(const QJsonObject& json)
{
    m_table->setRowCount(0);

    QJsonArray schedules = json["schedules"].toArray();
    for (const QJsonValue& value : schedules) {
        QJsonObject schedule = value.toObject();

        int row = m_table->rowCount();
        m_table->insertRow(row);

        // 时间
        QString timeValue = schedule["time"].toString();

        QTableWidgetItem* timeItem = new QTableWidgetItem(timeValue);
        timeItem->setData(Qt::UserRole, timeValue);
        m_table->setItem(row, 0, timeItem);

        // 任务
        m_table->setItem(row, 1, new QTableWidgetItem(schedule["task"].toString()));

        // 反思
        m_table->setItem(row, 2, new QTableWidgetItem(schedule["reflection"].toString()));
        
        // 目标
        QTableWidgetItem* goalItem = new QTableWidgetItem(schedule["goal"].toString());
        goalItem->setFlags(goalItem->flags() | Qt::ItemIsEditable);
        m_table->setItem(row, 3, goalItem);

        // 状态
        QTableWidgetItem* statusItem = new QTableWidgetItem();
        bool completed = schedule["completed"].toBool();
        statusItem->setCheckState(completed ? Qt::Checked : Qt::Unchecked);
        statusItem->setText(completed ? "已完成" : "未完成");
        m_table->setItem(row, 4, statusItem);
    }

    // 重新连接状态改变信号
    connect(m_table->model(), &QAbstractItemModel::dataChanged,
        [this](const QModelIndex& topLeft, const QModelIndex& bottomRight) {
            if (topLeft.column() == 4) {
                updateStatistics();
                saveScheduleForDate(m_currentDate);
            }
        });
}

void DailySchedule::updateStatistics()
{
    int totalTasks = m_table->rowCount();
    int completedTasks = 0;

    for (int i = 0; i < totalTasks; ++i) {
        QTableWidgetItem* item = m_table->item(i, 4);
        if (item != nullptr && item->checkState() == Qt::Checked) {
            completedTasks++;
        }
    }

    int productivity = totalTasks > 0 ? (completedTasks * 100) / totalTasks : 0;

    m_totalTasksLabel->setText(QString("总任务: %1").arg(totalTasks));
    m_completedLabel->setText(QString("已完成: %1").arg(completedTasks));
    m_productivityLabel->setText(QString("效率: %1%").arg(productivity));

    // 根据效率改变颜色
    QString color;
    if (productivity >= 80) color = "#4CAF50";
    else if (productivity >= 60) color = "#FF9800";
    else color = "#F44336";

    m_productivityLabel->setStyleSheet(
        QString("QLabel { font-size: 14px; font-weight: bold; padding: 8px; background-color: %1; color: white; border-radius: 4px; }").arg(color));
}